package com.blustreaksw.cyclecoach.history;

import java.util.ArrayList;
import java.util.UUID;
import android.content.Context;
import android.util.Log;

import com.blustreaksw.cyclecoach.R;
import com.blustreaksw.cyclecoach.data.UserProfile;
import com.blustreaksw.cyclecoach.data.WorkoutDatabaseHelper;

public class WorkoutHistoryContainer {
    private ArrayList<WorkoutLogEntry> mWorkoutHistory;
    private static final String TAG = "WorkoutHistoryContainer";

    private static WorkoutHistoryContainer sWorkoutHistoryContainer;
    private Context mAppContext;
    WorkoutDatabaseHelper mWorkoutDb;
    private long mUserId;
    private boolean mIsMetricUnits;

    private WorkoutHistoryContainer(Context appContext) {
        mAppContext = appContext;
        mWorkoutHistory = new ArrayList<WorkoutLogEntry>();
        mWorkoutDb = WorkoutDatabaseHelper.getInstance(mAppContext);
        mUserId = 0;
        mIsMetricUnits = true;
    }
    
    public void refreshContainer() {
    	mWorkoutDb.getWorkoutSessionSummariesForUser(mWorkoutHistory, mUserId);
    	
    	
    	if(mWorkoutHistory.size() > 0) {
    		for(WorkoutLogEntry w : mWorkoutHistory) {
    			if(w == null) {
    				Log.d(TAG, "refreshContainer - mWorkoutHistory returned null");
    			}
    			if(w.getId() == null) {
    				Log.d(TAG, "w.getId() returned null");
    			}
    			Log.d(TAG, String.format("UUID: %s, sessionId %d", w.getId().toString(), w.getSessionId()));
    		}
    	}
    }
    
    public void changeUserId(long userId) {
    	mUserId = userId;
    }

    public static WorkoutHistoryContainer getInstance(Context c) {
        if (sWorkoutHistoryContainer == null) {
        	sWorkoutHistoryContainer = new WorkoutHistoryContainer(c.getApplicationContext());
        }
        
        return sWorkoutHistoryContainer;
    }
    
    public static void setMeasurementUnits(boolean isMetricUnits) {
    	if (sWorkoutHistoryContainer != null) {
    		sWorkoutHistoryContainer.mIsMetricUnits = isMetricUnits;
    	}
    }
    
    public static boolean useMetricUnits() {
    	
    	if (sWorkoutHistoryContainer != null) {
    		return sWorkoutHistoryContainer.mIsMetricUnits;
    	}
    	
    	return true;
    }

    public WorkoutLogEntry getLogEntry(UUID id) {
        for (WorkoutLogEntry w : mWorkoutHistory) {
            if (w.getId().equals(id))
                return w;
        }
        return null;
    }
    
    public WorkoutLogEntry getLogEntry(int sessionId) {
    	return mWorkoutDb.createWorkoutLogEntryFromWorkoutSummaryTable(sessionId);
    }
    
    public ArrayList<WorkoutLogEntry> getAllLogEntries() {
        return mWorkoutHistory;
    }
    
    public void deleteLogEntry(WorkoutLogEntry w) {
    	mWorkoutHistory.remove(w);
    	mWorkoutDb.deleteWorkoutSession(w.getSessionId());
    }
}
